package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.sun.el.parser.AstBracketSuffix;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理文件上传下载
 */
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String BASE_PATH;

    /**
     * 文件上传
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) throws Exception {
        //1. 判断文件夹是否存在
        File dirFile = new File(BASE_PATH);
        if (!dirFile.exists()) {
            //说明目录不存在，就需要创建文件夹
            dirFile.mkdirs();
        }

        //2. 生产唯一UUID文件名称
        String uuid = UUID.randomUUID().toString();
        //截取原始文件名的后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uuidFileName = uuid + suffix;

        //3. 将文件上传到指定位置
        file.transferTo(new File(BASE_PATH + "/" + uuidFileName));

        //4. 响应文件名称的数据
        return R.success(uuidFileName);
    }


    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //1. 准备输入流
        FileInputStream is = new FileInputStream(BASE_PATH + "/" + name);
        //2. 输出流，response
        ServletOutputStream os = response.getOutputStream();
        //3. 输入流和输出流的对接，输入流：服务器的文件，输出流：response
        IOUtils.copy(is, os);
        is.close();
    }
}
